package com.example.onlinemallsystem.controller;

import com.example.onlinemallsystem.entity.User;
import com.example.onlinemallsystem.service.UserService;
import com.example.onlinemallsystem.service.ex.*;
import com.example.onlinemallsystem.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/Users")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
@Validated
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    //注册
    @PostMapping("reg")
    public JsonResult<Void> reg(@RequestBody User user) {
        try {
            if (!isValidUserType(user.getUserType())) {
                return new JsonResult<>(400, "无效的用户类型");
            }
            userService.reg(user);
            return new JsonResult<>(200, "注册成功");
        } catch (UsernameDuplicatedException e) {
            return new JsonResult<>(400, "用户名已存在");
        } catch (Exception e) {
            return new JsonResult<>(500, "注册失败，请稍后再试");
        }
    }

    private boolean isValidUserType(String userType) {
        return userType != null &&
                (userType.equals("buyer") ||
                        userType.equals("seller") ||
                        userType.equals("admin"));
    }

    @PostMapping("login")
    public JsonResult<User> login(@RequestBody User user, HttpSession session) {
        try {
            User loginUser = userService.login(user.getUsername(), user.getPassword(), user.getUserType());
            if (loginUser != null) {
                session.setAttribute("userId", loginUser.getId());
                session.setAttribute("username", loginUser.getUsername());
                session.setAttribute("userType", loginUser.getUserType()); // 关键：用loginUser.getUserType()
                return new JsonResult<User>(200, "登录成功", loginUser);
            } else {
                return new JsonResult<User>(401, "用户名、密码或用户类型错误", null);
            }
        } catch (UserNotFoundException | PasswordNotMatchException e) {
            return new JsonResult<User>(401, e.getMessage(), null);
        } catch (Exception e) {
            return new JsonResult<User>(500, "登录失败：" + e.getMessage(), null);
        }
    }

    @GetMapping("getById")
    public JsonResult<User> getById(HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            return new JsonResult<>(401, "用户未登录", null);
        }
        try {
            User data = userService.getById(userId);
            if (data == null) {
                return new JsonResult<>(404, "用户不存在", null);
            }
            return new JsonResult<User>(200, "获取成功", data);
        } catch (Exception e) {
            return new JsonResult<User>(500, "获取用户信息失败: " + e.getMessage(), null);
        }
    }

    @PostMapping("changeInfo")
    public JsonResult<Void> changeInfo(@RequestBody User userInfo, HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            return new JsonResult<>(401, "用户未登录");
        }
        try {
            User updateUser = new User();
            updateUser.setId(userId);
            if (userInfo.getUsername() != null && !userInfo.getUsername().trim().isEmpty()) {
                updateUser.setUsername(userInfo.getUsername().trim());
            }
            if (userInfo.getPhone() != null && !userInfo.getPhone().trim().isEmpty()) {
                updateUser.setPhone(userInfo.getPhone().trim());
            }
            if (userInfo.getEmail() != null && !userInfo.getEmail().trim().isEmpty()) {
                updateUser.setEmail(userInfo.getEmail().trim());
            }
            if (userInfo.getAddress() != null && !userInfo.getAddress().trim().isEmpty()) {
                updateUser.setAddress(userInfo.getAddress().trim());
            }
            userService.changeInfo(updateUser);
            User updatedUser = userService.getById(userId);
            if (updatedUser != null && updatedUser.getUsername() != null) {
                session.setAttribute("username", updatedUser.getUsername());
            }
            return new JsonResult<>(200, "用户信息更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult<>(500, "更新失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有用户列表（管理员功能）
     */
    @GetMapping("all")
    public JsonResult<List<User>> getAllUsers(HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            return new JsonResult<>(401, "用户未登录");
        }
        try {
            User currentUser = userService.getById(userId);
            List<User> users = userService.getAllUsers();
            return new JsonResult<>(200, "获取成功", users);
        } catch (Exception e) {
            return new JsonResult<>(500, "获取用户列表失败: " + e.getMessage());
        }
    }

    /**
     * 删除用户（管理员功能）
     */
    @DeleteMapping("{id}")
    public JsonResult<Void> deleteUser(@PathVariable Long id, HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");
        if (userId == null) {
            return new JsonResult<>(401, "用户未登录");
        }
        try {
            User currentUser = userService.getById(userId);
            if (userId.equals(id)) {
                return new JsonResult<>(400, "不能删除自己的账户");
            }
            userService.deleteUser(id);
            return new JsonResult<>(200, "删除成功");
        } catch (Exception e) {
            return new JsonResult<>(500, "删除失败: " + e.getMessage());
        }
    }
}
